import java.util.*;

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode cur1 = pHead1;
        int size1 = 0;
        while (cur1 != null) {
            size1++;
            cur1 = cur1.next;
        }
        ListNode cur2 = pHead2;
        int size2 = 0;
        while (cur2 != null) {
            size2++;
            cur2 = cur2.next;
        }
        
        cur1 = pHead1;
        cur2 = pHead2;
        int diff = size1 - size2;
        if (diff >= 0) {

            while (diff-- > 0) {
                cur1 = cur1.next;
            }
        } else {
            while (diff++ < 0) {
                cur2 = cur2.next;
            }
        }
        return find(cur1, cur2);
    }

    private ListNode find(ListNode cur1, ListNode cur2) {
        while (cur1 != null && cur2 != null) {
            if (cur1 == cur2) {
                return cur1;
            }
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return null;
    }
}
